//
//  CreatGroupViewController.m
//  FLORIDA
//
//  Created by 魏延(颜魏) on 2023/8/4.
//

#import "CreatGroupViewController.h"
#import "BlutoothGroupModel.h"
#import "ProgressHUD.h"

@interface CreatGroupViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *desLabel;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UILabel *numLabel;
@property (weak, nonatomic) IBOutlet UIButton *downBtn;

@property (weak, nonatomic) IBOutlet UIView *confirmBgView;
@property (weak, nonatomic) IBOutlet UILabel *confirmLabel;

@end

@implementation CreatGroupViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(valueChanged) name:UITextFieldTextDidChangeNotification object:nil];
    
    self.confirmLabel.text = [NSString stringWithFormat:@"Do you want to be the owner of the battery %@?", self.battery.name];
    
    // 0.创建组  1.修改组名  2.修改电池名
    if (self.type == 1) {
        self.titleLabel.text = @"Edit Group";
        [self.downBtn setTitle:@"Edit" forState:UIControlStateNormal];
        self.nameTF.text = self.group.groupName;
        self.numLabel.text = [NSString stringWithFormat:@"%ld/20", self.nameTF.text.length];
    }else if (self.type == 2) {
        self.titleLabel.text = @"Edit Group";
        self.desLabel.text = @"Battery name";
        self.nameTF.placeholder = @"Enter battery name";
        [self.downBtn setTitle:@"Edit" forState:UIControlStateNormal];
        self.nameTF.text = self.battery.cusName;
        self.numLabel.text = [NSString stringWithFormat:@"%ld/20", self.nameTF.text.length];
    }
}

- (void)valueChanged {
    self.numLabel.text = [NSString stringWithFormat:@"%ld/20", self.nameTF.text.length];
}

- (IBAction)ationCreate:(id)sender {
    [self.nameTF resignFirstResponder];
    if (self.nameTF.text.length) {
        self.confirmBgView.hidden = NO;
    }
}

- (IBAction)actionOk:(id)sender {
    self.confirmBgView.hidden = YES;
    [self mofifyContent];
}

- (IBAction)actionNo:(id)sender {
    self.confirmBgView.hidden = YES;
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)mofifyContent {
    // 0.创建组  1.修改组名  2.修改电池名
    if (self.type == 0) {
        NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
        NSMutableArray *array = [NSMutableArray array];
        if (groupStr.length) {
            NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
            [array addObjectsFromArray:dataArray];
        }
        BOOL canAdd = YES;
        for (BlutoothGroupModel *model in array) {
            if ([model.groupName isEqualToString:self.nameTF.text]) {
                canAdd = NO;
            }
        }
        if (!canAdd) {
            [ProgressHUD showErrorMessage:@"Group name already exists"];
            return;
        }
        BlutoothGroupModel *model = [[BlutoothGroupModel alloc] init];
        NSDate *date = [NSDate date];
        model.groupId = @([date timeIntervalSince1970]).description;
        model.groupName = self.nameTF.text;
        model.bluList = @[self.battery];
        [array addObject:model];
        NSString *str = [BlutoothGroupModel toJson:array];
        [[NSUserDefaults standardUserDefaults] setObject:str forKey:BatteryGroupBluList];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [ProgressHUD showSuccessMessage:@"Group created successfully"];
    }else if (self.type == 1) {
        NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
        NSMutableArray *array = [NSMutableArray array];
        if (groupStr.length) {
            NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
            [array addObjectsFromArray:dataArray];
        }
        for (BlutoothGroupModel *model in array) {
            if ([model.groupId isEqualToString:self.group.groupId]) {
                model.groupName = self.nameTF.text;
            }
        }
        NSString *str = [BlutoothGroupModel toJson:array];
        [[NSUserDefaults standardUserDefaults] setObject:str forKey:BatteryGroupBluList];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [ProgressHUD showSuccessMessage:@"Group rename successfully"];
    }else {
        NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
        NSMutableArray *array = [NSMutableArray array];
        if (groupStr.length) {
            NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
            [array addObjectsFromArray:dataArray];
        }
        for (BlutoothGroupModel *model in array) {
            for (BlutoothModel *blu in model.bluList) {
                if ([blu.name isEqualToString:self.battery.name]) {
                    blu.cusName = self.nameTF.text;
                }
            }
        }
        NSString *str = [BlutoothGroupModel toJson:array];
        [[NSUserDefaults standardUserDefaults] setObject:str forKey:BatteryGroupBluList];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [ProgressHUD showSuccessMessage:@"Battery rename successfully"];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kBTBluGroupChanged object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    });
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.text.length + string.length >= 20) {
        return NO;
    }else {
        return YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    return [textField resignFirstResponder];
}


@end
